import React, { useState } from 'react';
import { Cascader } from 'antd';
import { request } from '../.umi/plugin-request/request';


export default function ClassCascader({ onChange, url }){
  const [cascadeOpt, setCascadeOpt] = useState([
    {"type":0,"value":"文化与旅游学院","label":"文化与旅游学院","isLeaf":false},
    {"type":0,"value":"化学化工学院","label":"化学化工学院","isLeaf":false},
    {"type":0,"value":"管理学院","label":"管理学院","isLeaf":false},
    {"type":0,"value":"国际教育学院","label":"国际教育学院","isLeaf":false},
    {"type":0,"value":"外国语学院","label":"外国语学院","isLeaf":false},
    {"type":0,"value":"教育学院","label":"教育学院","isLeaf":false},
    {"type":0,"value":"数理学院","label":"数理学院","isLeaf":false},
    {"type":0,"value":"机械工程学院","label":"机械工程学院","isLeaf":false},
    {"type":0,"value":"材料工程学院","label":"材料工程学院","isLeaf":false},
    {"type":0,"value":"汽车与交通工程学院","label":"汽车与交通工程学院","isLeaf":false},
    {"type":0,"value":"电气信息工程学院","label":"电气信息工程学院","isLeaf":false},
    {"type":0,"value":"艺术设计学院","label":"艺术设计学院","isLeaf":false},
    {"type":0,"value":"计算机工程学院","label":"计算机工程学院","isLeaf":false},
    {"type":0,"value":"经济学院","label":"经济学院","isLeaf":false},
    {"type":0,"value":"资源与环境工程学院","label":"资源与环境工程学院","isLeaf":false}
  ]);

  const loadData = selectedOptions => {
    const targetOption = selectedOptions[selectedOptions.length - 1];
    targetOption.loading = true;
    let type = targetOption.type;
    let params = "";
    switch (type)
    {
      case 0:
        params = {college_name: targetOption.value}
        break;
      case 1:
        params = {discipline_name: targetOption.value, college_name: targetOption.parentValue}
        break;
    }
    request(url || 'http://t.onionnet.work/api/getCascadeSelect', {
      method: 'GET',
      params: params
    })
      .then(function(response) {
        if (response){
          let opt = [];
          response.data.forEach(value => {
            opt.push({
              parentValue: targetOption.value,
              type: type + 1,
              value: value,
              label: value,
              isLeaf: (type+1) === 2,
            })
          })
          targetOption.children = opt;
          targetOption.loading = false;
          setCascadeOpt([...cascadeOpt])
        }
      })
  }

  return (
    <Cascader
      style={{width: '320px'}}
      placeholder={'请选择想要查询的班级'}
      options={cascadeOpt}
      loadData={loadData}
      onChange={onChange}
      changeOnSelect
    />
  );
}
